package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-23
 * Time: 22:24
 */
public class Demo17 {

    private static int count = 0;

    public static void main1(String[] args) throws InterruptedException {
        Object locker = new Object();

        Thread thread1 = new Thread(() -> {
            //两个线程的整个for循环i< 50000 i++ count++都是互斥的 只能等thread1先执行完才能执行thread2
            //也就是真正意义上的串行执行
            synchronized (locker) {
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (locker) {
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("count: " + count);

    }

    public static void main(String[] args) throws InterruptedException {

        Thread thread1 = new Thread(() -> {
            Thread cur = Thread.currentThread();
            for (int i = 0; i < 50000; i++) {
                synchronized (cur) {
                    count++;
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            //Thread cur = Thread.currentThread();
            for (int i = 0; i < 50000; i++) {
                synchronized (thread1) {
                    count++;
                }
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("count: " + count);

    }
}
